<template>
  <div class="dept-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-card class="search-card">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="部门名称" prop="deptName">
            <el-input
              v-model="queryParams.deptName"
              placeholder="请输入部门名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="部门状态" clearable>
              <el-option label="正常" value="1" />
              <el-option label="停用" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    
    <!-- 操作按钮区域 -->
    <div class="action-container">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
      <el-button icon="el-icon-edit" :disabled="single" @click="handleUpdate">修改</el-button>
      <el-button 
        type="danger" 
        icon="el-icon-delete" 
        :disabled="multiple" 
        @click="handleDelete"
      >删除</el-button>
      <el-button icon="el-icon-refresh" @click="handleExpandAll">展开/折叠</el-button>
    </div>
    
    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="deptList"
        row-key="id"
        :tree-props="{ children: 'children' }"
        :default-expand-all="isExpandAll"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="部门名称" prop="deptName" :show-overflow-tooltip="true" />
        <el-table-column label="排序" prop="orderNum" width="80" align="center" />
        <el-table-column label="负责人" prop="leader" :show-overflow-tooltip="true" />
        <el-table-column label="联系电话" prop="phone" :show-overflow-tooltip="true" />
        <el-table-column label="邮箱" prop="email" :show-overflow-tooltip="true" />
        <el-table-column label="状态" prop="status" width="100" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="160" align="center" />
        <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="text" icon="el-icon-plus" @click="handleAdd(scope.row)">新增</el-button>
            <el-button 
              type="text" 
              icon="el-icon-delete" 
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 部门表单对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="上级部门">
          <el-tree-select
            v-model="form.parentId"
            :data="deptOptions"
            :props="{ label: 'deptName', value: 'id' }"
            placeholder="选择上级部门"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="deptName">
          <el-input v-model="form.deptName" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="显示排序" prop="orderNum">
          <el-input-number v-model="form.orderNum" :min="0" controls-position="right" />
        </el-form-item>
        <el-form-item label="负责人" prop="leader">
          <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
        </el-form-item>
        <el-form-item label="部门状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 加载状态
const loading = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 是否展开所有
const isExpandAll = ref(true)
// 弹出层标题
const title = ref('')
// 是否显示弹出层
const open = ref(false)
// 部门表格数据
const deptList = ref([])
// 部门树选项
const deptOptions = ref([])

// 查询参数
const queryParams = reactive({
  deptName: undefined,
  status: undefined
})

// 表单参数
const form = reactive({
  id: undefined,
  parentId: 0,
  deptName: undefined,
  orderNum: 0,
  leader: undefined,
  phone: undefined,
  email: undefined,
  status: 1
})

// 表单校验
const rules = {
  deptName: [
    { required: true, message: '部门名称不能为空', trigger: 'blur' }
  ],
  orderNum: [
    { required: true, message: '显示排序不能为空', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 模拟数据
const mockDeptList = [
  {
    id: 1,
    deptName: '总公司',
    orderNum: 1,
    leader: '张三',
    phone: '13800138000',
    email: 'zhangsan@example.com',
    status: 1,
    createTime: '2023-01-01 00:00:00',
    children: [
      {
        id: 2,
        deptName: '研发部门',
        orderNum: 1,
        leader: '李四',
        phone: '13800138001',
        email: 'lisi@example.com',
        status: 1,
        createTime: '2023-01-01 00:00:00',
        children: [
          {
            id: 5,
            deptName: '前端组',
            orderNum: 1,
            leader: '王五',
            phone: '13800138002',
            email: 'wangwu@example.com',
            status: 1,
            createTime: '2023-01-01 00:00:00'
          },
          {
            id: 6,
            deptName: '后端组',
            orderNum: 2,
            leader: '赵六',
            phone: '13800138003',
            email: 'zhaoliu@example.com',
            status: 1,
            createTime: '2023-01-01 00:00:00'
          }
        ]
      },
      {
        id: 3,
        deptName: '市场部门',
        orderNum: 2,
        leader: '钱七',
        phone: '13800138004',
        email: 'qianqi@example.com',
        status: 1,
        createTime: '2023-01-01 00:00:00'
      },
      {
        id: 4,
        deptName: '财务部门',
        orderNum: 3,
        leader: '孙八',
        phone: '13800138005',
        email: 'sunba@example.com',
        status: 1,
        createTime: '2023-01-01 00:00:00'
      }
    ]
  }
]

// 查询部门列表
const getList = () => {
  loading.value = true
  // 模拟接口请求
  setTimeout(() => {
    deptList.value = mockDeptList
    loading.value = false
  }, 500)
}

// 表单重置
const reset = () => {
  form.id = undefined
  form.parentId = 0
  form.deptName = undefined
  form.orderNum = 0
  form.leader = undefined
  form.phone = undefined
  form.email = undefined
  form.status = 1
}

// 搜索按钮操作
const handleQuery = () => {
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryParams.deptName = undefined
  queryParams.status = undefined
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 展开/折叠操作
const handleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value
}

// 新增按钮操作
const handleAdd = (row) => {
  reset()
  if (row && row.id) {
    form.parentId = row.id
  }
  getDeptTree()
  open.value = true
  title.value = '添加部门'
}

// 修改按钮操作
const handleUpdate = (row) => {
  reset()
  const deptId = row?.id || ids.value[0]
  // 模拟获取部门详情
  const findDeptById = (list, id) => {
    for (let item of list) {
      if (item.id === id) {
        return item
      }
      if (item.children && item.children.length > 0) {
        const found = findDeptById(item.children, id)
        if (found) return found
      }
    }
    return null
  }
  
  const deptInfo = findDeptById(mockDeptList, deptId)
  if (deptInfo) {
    Object.assign(form, deptInfo)
  }
  
  getDeptTree()
  open.value = true
  title.value = '修改部门'
}

// 获取部门树
const getDeptTree = () => {
  // 模拟获取部门树
  deptOptions.value = [
    {
      id: 0,
      deptName: '顶级部门',
      children: mockDeptList
    }
  ]
}

// 提交按钮
const submitForm = () => {
  // 模拟提交
  ElMessage.success(form.id ? '修改成功' : '新增成功')
  open.value = false
  getList()
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 删除按钮操作
const handleDelete = (row) => {
  const deptIds = row?.id ? [row.id] : ids.value
  
  ElMessageBox.confirm('确认删除已选中的部门?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟删除
    ElMessage.success('删除成功')
    getList()
  }).catch(() => {})
}

// 部门状态修改
const handleStatusChange = (row) => {
  const text = row.status === 1 ? '启用' : '停用'
  ElMessageBox.confirm(`确认要${text}该部门吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟修改状态
    ElMessage.success(`${text}成功`)
  }).catch(() => {
    row.status = row.status === 1 ? 0 : 1
  })
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.dept-container {
  padding: 0;
}

.search-container {
  margin-bottom: 20px;
}

.search-card {
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
}

.action-container {
  margin-bottom: 20px;
}

.table-card {
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
}
</style> 